# -*- coding:utf-8 -*-

import os
import models
import forms
import datetime

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.api import images

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db


#class AuthorHandler(webapp.RequestHandler):
#    def get(self):
#        user = users.get_current_user()
#        if user:
#            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
#        else:
#            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
#        
#        author = db.Query(models.Author)
#        author = author.filter('user =', user)
#        author_list = author.fetch(limit = 1)
#        
#        path = os.path.join(os.path.dirname(__file__), 'templates/author.html')
#        self.response.out.write(template.render(path, locals(), debug = True))
class DeleteBookHandler(webapp.RequestHandler):
    def get(self):
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_book = models.Book.get(db.Key.from_path('Book', id))
            chosen_book.delete()
            self.redirect('/library')
        else:
            self.redirect('library')

class LibraryHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
        
        author = db.Query(models.Author)
        author = author.filter('user =', user)
        author_list = author.fetch(limit = 1)
        
        book = db.Query(models.Book)
        for author in author_list:
            book = book.filter('author =', author)
        book_list = book.fetch(limit = 100)
        book_list.reverse()
        
        path = os.path.join(os.path.dirname(__file__), 'templates/library.html')
        self.response.out.write(template.render(path, locals(), debug = True))

class SaveBookHandler(webapp.RequestHandler):
    def post(self):
        if self.request.get('chosen_book'):
            id = int(self.request.get('chosen_book'))
            book = models.Book.get(db.Key.from_path('Book', id))
        else:
            book = models.Book()
        
        data = forms.BookForm(data = self.request.POST)
        if data.is_valid():
            if self.request.get('file'):
                book.file = db.Blob(self.request.get('file'))
            book.title = self.request.get('title')
            
            author_list = models.Author.all()
            author_list.filter('user =', users.get_current_user())
            for author in author_list:
                book.author = author.key()
            book.isbn = self.request.get('isbn')
            
            book_category = models.Category()
            book_category.name = self.request.get('name') 
            
            book.language = self.request.get('language')
            book.details = self.request.get('details')
            book.content = self.request.get('content')
            book.year = self.request.get('year')
            book.price = float(self.request.get('price'))
            book.currency = self.request.get('currency')
            book.total_pages = int(self.request.get('total_pages'))
            
            book.put()
            self.redirect('/library')
        else:
            self.redirect('/save_book')
        
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
        
        language_list = models.Book.language.choices
        currency_list = models.Book.currency.choices
        
#        rating_list = []
#        
#        for rating in range(1, 6):
#            rating_list.append(rating)
#        
#        rating_list.reverse()
        name_list = models.Category.all()
        
        author = db.Query(models.Author)
        author = author.filter('user =', user)
        author_list = author.fetch(limit =1)
        
#        if self.request.GET.has_key('id'):
#            id = int(self.request.GET['id'])
#            chosen_book_category = models.Category.get(db.Key.from_path('Category', id))
        
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_book = models.Book.get(db.Key.from_path('Book', id))
        
        path = os.path.join(os.path.dirname(__file__), 'templates/save_book.html')
        self.response.out.write(template.render(path, locals(), debug = True))

class GetPhoto(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        author = db.Query(models.Author)
        author = author.filter('user =', user)
        author_list = author.fetch(limit =1)
        self.response.headers['Content-Type'] = 'image/png'
        for author in author_list:
            self.response.out.write(author.photo)

class DeleteAuthorHandler(webapp.RequestHandler):
    def get(self):
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_author = models.Author.get(db.Key.from_path('Author', id))
            chosen_author.delete()
            self.redirect('/profile')
        else:
            self.redirect('/profile')

class SaveAuthorHandler(webapp.RequestHandler):
    def post(self):
        if self.request.get('chosen_author'):
            id = int(self.request.get('chosen_author'))
            author = models.Author.get(db.Key.from_path('Author', id))
        else:
            author = models.Author()
        
        data = forms.AuthorForm(data = self.request.POST)
        if data.is_valid():
            if users.get_current_user():
                author.user = users.get_current_user()
            
#            password = self.request.get('password')
#            re_password = self.request.get('re_password')
#            
#            password = password.strip()
#            re_password = re_password.strip()
#            
#            if password != '' and re_password != '':
#                if password.lower() == re_password.lower():
#                    author.password = password.lower()
#                else:
#                    self.redirect('/save_author')
#            else:
#                self.redirect('/save_author')
                
            author.biography = self.request.get('biography')
            if self.request.get('photo'):
                photo = images.resize(self.request.get('photo'), 32, 32)
                author.photo = db.Blob(photo)
            else:
                self.redirect('/save_author')
            author.put()
            self.redirect('/library')
        
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
        
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_author = models.Author.get(db.Key.from_path('Author', id))
        
        path = os.path.join(os.path.dirname(__file__), 'templates/save_author.html')
        self.response.out.write(template.render(path, locals(), debug = True))

class DeleteProfileHandler(webapp.RequestHandler):
    def get(self):
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_account = models.Account.get(db.Key.from_path('Account', id))
            chosen_account.delete()
            self.redirect('/profile')
        else:
            self.redirect('/profile')

class SaveProfileHandler(webapp.RequestHandler):
    def post(self):
        if self.request.get('chosen_account'):
            id = int(self.request.get('chosen_account'))
            account = models.Account.get(db.Key.from_path('Account', id))
        else:
            account = models.Account()
        
        
        data = forms.AccountForm(data = self.request.POST)
        if data.is_valid():
            if users.get_current_user():
                account.user = users.get_current_user()
            
            account.firstname = self.request.get('firstname')
            account.lastname = self.request.get('lastname')
            account.gender = self.request.get('gender')
            year = int(self.request.get('year'))
            month = int(self.request.get('month'))
            day = int(self.request.get('day'))
            account.birthdate = datetime.date(year, month, day)
            account.phone = self.request.get('phone')
            account.email = self.request.get('email')
            account.country = self.request.get('country')
            account.city = self.request.get('city')
            account.address = self.request.get('address')
            account.postal = self.request.get('postal')
            account.profession = self.request.get('profession')
            
            account.put()
            self.redirect('/profile')
        else:
#            self.response.out.write(data)
            path = os.path.join(os.path.dirname(__file__), 'templates/save_profile.html')
            self.response.out.write(template.render(path, locals(), debug = True))
        
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
        
#        accountForm = ("<form method=\"POST\" action=\"\"><table>%s</table><input type=\"submit\" value=\"Хадгалах\" /></form>" %(forms.AccountForm()))
        
        account = db.Query(models.Account)
        account = account.filter('user =', user)
        account_list = account.fetch(limit = 1)
        
        gender_list = models.Account.gender.choices
        profession_list = models.Account.profession.choices
        
        year_list = []
        month_list = []
        day_list = []
        
        for year in range(1930, 2010):
            year_list.append(year)
            
        for month in range(1, 13):
            month_list.append(month)
            
        for day in range(1, 32):
            day_list.append(day)
            
        year_list.reverse()
        
        
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_account = models.Account.get(db.Key.from_path('Account', id))
        
        path = os.path.join(os.path.dirname(__file__), 'templates/save_profile.html')
        self.response.out.write(template.render(path, locals(), debug = True))

class ProfileHandler(webapp.RequestHandler):
#    def post(self):
#        data = AccountForm(data = self.request.POST)
#        if data.is_valid():
#            entity = data.save(commit = False)
#            entity.user = users.get_current_user()
#            entity.put()
#            self.redirect('/')
#        else:
#            user = users.get_current_user()
#            if user:
#                greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
#            else:
#                greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
#            
#            accountForm = ("<form method=\"POST\" action=\"\"><table>%s</table><input type=\"submit\" value=\"Хадгалах\" /></form>" %(data))
#            
#            account = db.Query(models.Account)
#            account = account.filter('user =', user)
#            account_list = account.fetch(limit = 1)
#            
#            path = os.path.join(os.path.dirname(__file__), 'templates/profile.html')
#            self.response.out.write(template.render(path, locals(), debug = True))
#    
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
        
#        accountForm = ("<form method=\"POST\" action=\"\"><table>%s</table><input type=\"submit\" value=\"Хадгалах\" /></form>" %(AccountForm()))
        
        account = db.Query(models.Account)
        account = account.filter('user =', user)
        account_list = account.fetch(limit = 1)
        
        author = db.Query(models.Author)
        author = author.filter('user =', user)
        author_list = author.fetch(limit = 1)
        
        path = os.path.join(os.path.dirname(__file__), 'templates/profile.html')
        self.response.out.write(template.render(path, locals(), debug = True))
        
        
class AdminHandler(webapp.RequestHandler):
    def post(self):
#        category = db.Query(models.Category)
#        category_list = category.fetch(limit = 100)
#        for category in category_list:
#            category.delete()
        if self.request.get('chosen_category'):
            id = int(self.request.get('chosen_category'))
            category = models.Category.get(db.Key.from_path('Category', id))
        else:
            category = models.Category()
        
        data = forms.CategoryForm(data = self.request.POST)
        if data.is_valid():
            category.name = self.request.get('name')
            category.maincategory = self.request.get('category')
            category.put()
            self.redirect("/admin")
        else:
            self.redirect("/admin")
    
    def get(self):
        admin = users.is_current_user_admin()
        if admin:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(admin, users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
        
        maincategory_list = models.Category.maincategory.choices
#        linteratuic_list = maincategory_list.filter("maincategory", u'Уран зохиол')
#        science_list = maincategory_list.filter("maincategory", u'Шижлэх ухаан')
#        other_list = maincategory_list.filter("maincategory", u'Бусад')
        
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_category = models.Category.get(db.Key.from_path('Category', id))
        
        category = db.Query(models.Category)
        category_list = category.fetch(limit = 50)
        
        path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
        self.response.out.write(template.render(path, locals(), debug = True))

class DeletCategoryHandler(webapp.RequestHandler):
    def get(self):
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_category = models.Category.get(db.Key.from_path('Category', id))
            chosen_category.delete()
            self.redirect('/admin')
        else:
            self.redirect('/admin')
            
class ProfessionHandler(webapp.RequestHandler):
    def post(self):
        if self.request.get('chosen_profession'):
            id = int(self.request.get('chosen_profession'))
            profession = models.Profession.get(db.Key.from_path('Profession', id))
        else:
            profession = models.Profession()
        data = forms.ProfessionForm(data = self.request.POST)
        if data.is_valid():
            profession.ProfessionName = self.request.get('ProfessionName')
            profession.put()
            self.redirect('/profession')
        else:
            self.redirect('/profession')
            
    def get(self):
        admin = users.is_current_user_admin()
        if admin:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(admin, users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
            
        
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            chosen_profession = models.Profession.get(db.Key.from_path('Profession', id))
        
        profession = db.Query(models.Profession)
        profession_list = profession.fetch(limit = 100)
#        db.delete(profession_list)
        
        path = os.path.join(os.path.dirname(__file__), 'templates/profession.html')
        self.response.out.write(template.render(path, locals(), debug = True))
        
class DeleteProfessionHandler(webapp.RequestHandler):
    def get(self):
        if self.request.GET.has_key('id'):
            id = int(self.request.GET['id'])
            profession_category = models.Profession.get(db.Key.from_path('Profession', id))
            profession_category.delete()
            self.redirect('/profession')
        else:
            self.redirect('/profession')

class BookCategoryHandler(webapp.RequestHandler):
    def post(self):
        category = models.Category()
        data = forms.CategoryForm(data = self.request.POST)
        if data.is_valid():
            category.name = self.request.get('name')
            category.put()
            self.redirect("/bookcategory")
        else:
            self.redirect("/bookcategory")
    
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
            
        name_list = models.Category.all()
        
        path = os.path.join(os.path.dirname(__file__), 'templates/BookCategory.html')
        self.response.out.write(template.render(path, locals(), debug = True))

class MainHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        
        if users.is_current_user_admin():
            self.redirect("/admin")
        
        if user:
            greeting = ("<ul><li><strong><b>%s </b></strong>|</li><li><a href=\"/profile\">Миний мэдээлэл </a>|</li><li><a href=\"%s\">Гарах</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
        else:
            greeting = ("<ul><li><a href=\"%s\">Нэвтрэх</a></li></ul>" %(users.create_login_url("/")))
        
        account = db.Query(models.Account)
        account = account.filter('user =', user)
        account_list = account.fetch(limit = 1)
        
        book = db.Query(models.Book)
        book_list = book.fetch(limit = 100)
        book_list.reverse()
        
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, locals(), debug = True))
        

application = webapp.WSGIApplication([
                                      ('/', MainHandler),
                                      ('/profile', ProfileHandler),
                                      ('/save_profile', SaveProfileHandler),
                                      ('/delete_profile', DeleteProfileHandler),
                                      ('/save_author', SaveAuthorHandler),
                                      ('/delete_author', DeleteAuthorHandler),
                                      ('/photo', GetPhoto),
                                      ('/library', LibraryHandler),
                                      ('/save_book', SaveBookHandler),
                                      ('/delete_book', DeleteBookHandler),
                                      ('/admin', AdminHandler),
                                      ('/delete_admin', DeletCategoryHandler),
                                      ('/profession', ProfessionHandler),
                                      ('/delete_pro',DeleteProfessionHandler),
                                      ('/bookcategory', BookCategoryHandler)
                                      ], debug = True)


def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()